type todoItemType = {
  id: number;
  task: string;
  isDone: boolean;
};

const initState = {
  lists: JSON.parse(
    localStorage.getItem('todo-lists') || '[]'
  ) as todoItemType[],
  // 断言
  type: (localStorage.getItem('todo-type') || 'all') as ToggleType,
};

export type ActionType =
  | {
      type: 'todo/delbyid';
      payload: number;
    }
  | {
      type: 'todo/clearIsDone';
    }
  | {
      type: 'todo/add';
      payload: string;
    }
  | {
      type: 'todo/allchecked';
      payload: boolean;
    }
  | {
      type: 'todo/singlechecked';
      payload: number;
    }
  | {
      type: 'todo/settype';
      payload: ToggleType;
    };

export type ToggleType = 'all' | 'completed' | 'active';

function todoReducer(state = initState, action: ActionType): typeof initState {
  console.log('action --->', action);

  switch (action.type) {
    case 'todo/delbyid':
      return {
        ...state,
        lists: state.lists.filter((item) => item.id !== action.payload),
      };
    case 'todo/clearIsDone':
      return {
        ...state,
        lists: state.lists.filter((item) => !item.isDone),
      };
    case 'todo/singlechecked':
      return {
        ...state,
        lists: state.lists.map((item) => ({
          ...item,
          isDone: item.id === action.payload ? !item.isDone : item.isDone,
        })),
      };
    case 'todo/add':
      return {
        ...state,
        lists: [
          { id: Date.now(), task: action.payload, isDone: false },
          ...state.lists,
        ],
      };
    case 'todo/allchecked':
      return {
        ...state,
        lists: state.lists.map((item) => ({ ...item, isDone: action.payload })),
      };
    case 'todo/settype':
      return {
        ...state,
        type: action.payload,
      };
    default:
      return state;
  }
}

export default todoReducer;
